#include "MLTrajectoryLoader.h"

CMLTrajectoryLoader::CMLTrajectoryLoader(void)
{
	m_nStartPos = -1;
	m_nEndPos = -1;
}

CMLTrajectoryLoader::~CMLTrajectoryLoader(void)
{
	if (m_FileStream.is_open())
		m_FileStream.close();
}

int CMLTrajectoryLoader::Initialize(const std::wstring& wstrFileName)
{
	m_FileStream.open(wstrFileName.c_str());
	if (m_FileStream.fail())
	{
		ML_ASSERT(false);
		return -1;
	}
	m_nPos = 0;
	if (m_nStartPos > 0)
	{
		std::wstring wstrLine;
		while(m_FileStream.eof() == false)
		{
			if (m_nPos == m_nStartPos)
				break;
			std::getline(m_FileStream, wstrLine);
			m_nPos++;
		}
	}

	return 0;
}

int CMLTrajectoryLoader::Load(CMLTrajectoryCollection& trajs)
{
	return Load(trajs, -1);
}

int CMLTrajectoryLoader::Load(CMLTrajectoryCollection& trajs, int nBufSize)
{
	int nSize = 0;
	std::wstring wstrLine;
	CMLTrajectory traj;
	std::wstring wszTrajName;
	std::wstring wszLastTrajName;

	if (nBufSize >= 0)
	{
		if (trajs.Count() < nBufSize)
			trajs.Resize(nBufSize);
	}

	while(m_FileStream.eof() == false && (nBufSize < 0 || nSize < nBufSize))
	{
		if (m_nPos == m_nEndPos)
			break;

		std::getline(m_FileStream, wstrLine);
		if (wstrLine.length() == 0) 
			break;

		mylablib::CMLTools::GetNextToken(wstrLine, wszTrajName);
		if (wszLastTrajName.length() == 0 || wszLastTrajName.compare(wszTrajName) != 0)
		{
			wszLastTrajName = wszTrajName;
			trajs.Add(traj);
			trajs.Back().SetName(wszTrajName);
		}

		mylablib::CMLDataPoint dataPoint;
		dataPoint.FromWString(wstrLine.substr(wszTrajName.length()));
		trajs.Back().AddPoint(dataPoint);

		nSize++;
		m_nPos++;
	}

	if (trajs.Count() > nSize)
	{
		trajs.Delete(nSize, trajs.Count() - nSize);
	}
	return 0;
}


void CMLTrajectoryLoader::Close()
{
	m_FileStream.close();
}
